package com.sweet.righere.sharedpreferencestest01;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity implements OnClickListener{

    SharedPreferences preferences;
    SharedPreferences.Editor editor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        preferences =getSharedPreferences("count",MODE_PRIVATE);
        editor = preferences.edit();

        Button mButton_write = (Button) findViewById(R.id.write_button);
        Button mButton_read = (Button) findViewById(R.id.read_button);

        if (mButton_read != null) {
            mButton_read.setOnClickListener(this);
        }

        if (mButton_write != null) {
            mButton_write.setOnClickListener(this);
        }

        editor.apply();
    }

    @Override
    public void onClick(View v) {

        //读取时间字符串数据
        String time = preferences.getString("time",null);
        //读取随机数整形数据
        int count = preferences.getInt("count",0);
        switch(v.getId()){
            //写入当前时间
            case R.id.write_button:
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"+"hh:mm:ss");
                //存入当前时间
                editor.putString("time", sdf.format(new Date()));
                //存入一个随机数
                editor.putInt("count", ++count);
                //提交存入的数据
                editor.commit();

            //读取显示当前时间
            case R.id.read_button:
                String result = time ==null?"你暂时还未输入数据":"你输入的当前时间是："+time+"你输入的随机数是："+count;
                //点击时toast到屏幕上
                Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
        }
    }
}
